import logoPng from '@/assets/Image/logo.png';
import { HomeOutlined, ShopOutlined } from '@ant-design/icons';
import { message } from 'antd';
import { RequestConfig, RequestOptions, history } from 'umi';
import RightRender from './loyout/RightRender';
import { getUserInfoApi, getUserPermissionListApi } from './services/api';
import { isJson } from './utils';
interface Node {
  id: number;
  children?: Node[];
  create_time?: string;
  value?: string;
  label?: string;
  leaf?: boolean;
  parent?: number;
  // ...其他属性
}
function flattenTree(tree: Node[]): Node[] {
  const result: Node[] = [];

  function traverse(node: Node) {
    result.push(node);
    if (node.children) {
      node.children.forEach((child) => traverse(child));
    }
  }

  tree.forEach((rootNode) => traverse(rootNode));
  return result;
}

// 运行时配置

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<any> {
  // 用户信息
  let _info: any = {};

  // 权限列表
  let _permissionList: any = [];
  const _token = localStorage.getItem('token');

  if (!_token) {
    history.push('/login');
    return;
  }
  try {
    _info = await getUserInfoApi();
    const list = await getUserPermissionListApi();
    _permissionList = flattenTree(list.data);
    console.log('_permissionList', {_permissionList,list});
  } catch (error) {}

  return { info: _info?.data ?? {} ,permissionList: _permissionList};
}

export const layout = () => {
  return {
    layout: 'mix',
    splitMenus: true,
    // colorPrimary: '#5A54F9', //antd主题色
    title: '换电管理系统',
    rightRender: () => <RightRender />,
    // 布局
    token: {
      header: {
        colorBgMenuItemSelected: 'rgba(0, 0, 0, 0.04)',
        // colorBgHeader: 'rgba(240, 242, 245, 0.4)',
        //	menuItem 的选中背景颜色
        // colorBgMenuItemSelected: 'rgb(230, 244, 255)',
        /*  // menuItem 的选中文字颜色 */
        colorTextMenuSelected: 'rgb(22, 119, 255)',
        colorBgHeader: 'transparent',
      },
      pageContainer: {
        paddingInlinePageContainerContent: 20,
        paddingBlockPageContainerContent: 12,
      },
      bgLayout: 'transparent',
      sider: {
        colorTextMenuSelected: 'rgb(22, 119, 255)',
        colorBgMenuItemSelected: 'rgba(0, 0, 0, 0.04)',
        colorTextMenuItemHover: 'rgba(0, 0, 0, 0.65)',
        colorBgCollapsedButton: '#fff',
      },
    },
    headerTitleRender: (logo, title, _) => {
      return (
        <span
          style={{
            fontFamily: '阿里巴巴普惠体Bold',
          }}
        >
          <img src={logoPng} alt="" />
          {title}
        </span>
      );
    },
    siderWidth: 178,
    menu: () => {
      return {
        collapsedButtonRender: false,
        collapsedShowTitle: false,
        collapsedWidth: 0,
        selectedKeys: ['/'],
        items: [
          {
            key: '/',
            icon: <HomeOutlined />,
            label: '首页',
          },
          {
            key: '/merchant',
            icon: <ShopOutlined />,
            label: '商户管理',
          },
        ],
      };
    },
  };
};

async function downloadFile(response: any) {
  //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
  let url = window.URL.createObjectURL(
    new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
    }),
  );
  const _config = isJson(response?.config?.data)
    ? JSON.parse(response?.config?.data)
    : response?.config?.data;

  // 设置的下载文件文件名
  let fileName =
    _config?.filename ??
    decodeURI(
      response?.headers?.['content-disposition']
        ?.split(';')?.[1]
        ?.split('filename=')[1],
    );

  // 创建A标签
  let link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;

  // 触发点击方法
  link.setAttribute('download', fileName);
  document.body.appendChild(link);
  link.click();

  return response;
}

export const request: RequestConfig = {
  baseURL: 'https://api.ynylny.com/',
  // baseURL: 'http://3ubqt8478312.vicp.fun',
  timeout: 6000000,
  errorConfig: {
    errorHandler(error) {
      if (error?.response?.status === 401) {
        message.error('身份认证失败,请重新登录');
        localStorage.clear();
        history.push('/login');
      }
    },
    errorThrower() {},
  },
  requestInterceptors: [
    (config: RequestOptions) => {
      config.headers = {
        ...config.headers,
        Authorization: `Bearer ${localStorage.getItem('token')}`,
      };

      return config;
    },
  ],
  responseInterceptors: [
    (response: any) => {
      const { data, headers } = response as any;

      if (headers && headers['content-type'] === 'application/vnd.ms-excel') {
        return downloadFile(response);
      }

      // 未登陆或认证失败
      if (data.code === 401) {
        message.error(data?.msg ? data?.msg : '身份认证失败,请重新登录');
        setTimeout(() => {
          localStorage.clear();
          history.push('/login');
        }, 200);
      }

      if (data.code === 1 || data.code === 400 || data.code === 1001) {
        message.error(data?.msg);
        return Promise.reject(data.msg || data.msg || data.error);
      }

      return response;
    },
  ],
};
